<?php

namespace App\Repositories\Criteria;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

/**
 * Class TimeFilterCriteria
 * @package namespace App\Repositories\Criteria;
 */
class TimeFilterCriteria implements CriteriaInterface
{
    protected $timeFilter = [];
    protected $field;

    public function __construct(Request $request, $field = 'created_at', $today = true)
    {
        $this->timeFilter['start_at'] = $request->input('start_at')? : ($today ? Carbon::now()->startOfDay()->toDateTimeString() : null);
        $this->timeFilter['end_at'] = $request->input('end_at')?$request->input('end_at').':59':($today ? Carbon::now()->endOfDay()->toDateTimeString() : null);
        $this->field = $field;
    }

    /**
     * Apply criteria in query repository
     *
     * @param                     $model
     * @param RepositoryInterface $repository
     *
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        if ( ! is_null($this->timeFilter['start_at'])) {
            $model =  $model->where($this->field, '>=', $this->timeFilter['start_at']);
        }
        if (! is_null($this->timeFilter['end_at'])) {
            $model = $model->where($this->field, '<=', $this->timeFilter['end_at']);
        }
        return $model;
    }
}
